# ------------------------------------- #
# Version: 9/20/2024
# Factor analysis of ethnocentrism and other measures in Qualtrics Survey
# ------------------------------------- #

# --- libraries --- #
library(psych)
set.seed(1912)

# --- load data
qualtrics_survey <- read.csv("../output/qualtrics_ethno.csv")
nrow(qualtrics_survey) # N = 1626
to_export <- data.frame(id = qualtrics_survey$id) # start a new data frame

# --- RPP ethnocentrism measure based on ethno1, ethno2, ethno3
ethno_items <- cbind(qualtrics_survey$ethno1,
                     qualtrics_survey$ethno2,
                     qualtrics_survey$ethno3)
ethno_fit <- fa(ethno_items, nfactors=1, rotate="varimax", scores=TRUE, fm="pa")
ethno_fit$loadings # loadings
to_export$e3f <- ethno_fit$scores[,1] # extract score
table(ifelse(to_export$e3f > median(to_export$e3f), 1, 0)) # tabulation

# --- Alternative ethnocentrism measure based on ethno4, ethno5
ethno_items <- cbind(qualtrics_survey$ethno4,
                     qualtrics_survey$ethno5)
ethno_fit <- fa(ethno_items, nfactors=1, rotate="varimax", scores=TRUE, fm="pa")
ethno_fit$loadings # loadings
to_export$e2f <- ethno_fit$scores[,1] # extract score
table(ifelse(to_export$e2f > median(to_export$e2f), 1, 0)) # tabulation

# --- Write out Data
write.csv(to_export, "../output/qualtrics_factorscores.csv")